package com.wzw.springboot.principle.use.security.controller;

import com.wzw.springboot.principle.use.security.dto.Login;
import com.wzw.springboot.principle.use.security.dto.Register;
import com.wzw.springboot.principle.use.security.entity.UserEntity;
import com.wzw.springboot.principle.use.security.enums.AuthenticationEnum;
import com.wzw.springboot.principle.use.security.infrastructure.model.SecurityRoles;
import com.wzw.springboot.principle.use.security.infrastructure.model.SecurityUser;
import com.wzw.springboot.principle.use.security.infrastructure.model.SecurityUserHolder;
import com.wzw.springboot.principle.use.security.service.UserAuthService;
import com.wzw.springboot.principle.use.security.service.UserDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Locale;

/**
 * @author Wangzhiwen
 */
@RestController("securityUserController")
@RequestMapping("/security/user")
@RequiredArgsConstructor
public class UserController {

    private final UserAuthService userAuthService;

    private final UserDataService userDataService;

    @PostMapping("/login")
    public String login(@RequestBody Login login) {
        return userAuthService.login(AuthenticationEnum.valueOf(login.getWay().toUpperCase(Locale.ROOT)), login.getAccount(), login.getPassword());
    }

    @PutMapping("/logout")
    public void logout(@RequestHeader(name = "UserId") String userId) {
        userAuthService.logout(Long.parseLong(userId));
    }

    @PostMapping("/register")
    public Boolean register(@RequestBody Register register) {
        return userDataService.registerUser(register);
    }

    @GetMapping("/{id}")
    public UserEntity userDetails(@PathVariable Long id) {
        return userDataService.details(id);
    }

    @GetMapping("/current")
    public SecurityUser currentUserEntity() {
        return SecurityUserHolder.get();
    }

    /**
     * 参数解析器
     *
     * @param securityUser value
     */
    @GetMapping("/current/info")
    public void currentUserInfo(SecurityUser securityUser) {
        System.out.println(securityUser);
    }

    /**
     * 角色注解与表达式
     */
    @GetMapping("/hasAnyRole")
    @Secured(SecurityRoles.ADMIN)
    public String hasAnyRole() {
        return "hasAnyRole";
    }

    @GetMapping("/preAuthorize")
    @PreAuthorize("hasAnyRole('admin')") // 会自动拼上ROLE_
    // @PreAuthorize("hasAnyAuthority('admin')") // 不会自动拼上ROLE_
    public String preAuthorize() {
        return "preAuthorize";
    }

    @GetMapping("/test")
    public boolean test() {
        return true;
    }
}
